package com.jiyinit.web.core.common.listener;

import com.jiyinit.web.core.common.constant.Constant;
import com.jiyinit.web.core.common.vo.CurrentUserVo;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lr on 2017/11/24.
 */
public class LoginListenner implements HttpSessionAttributeListener {
    /**
     * 用于存放账号和session对应关系的map
     */
    private Map<String, HttpSession> map = new HashMap<String, HttpSession>();

    /**
     * 当向session中放入数据触发
     */
    public void attributeAdded(HttpSessionBindingEvent event) {
        String name = event.getName();

        if (name.equals(Constant.CURRENT_LOGIN_USER_NAME)) {
            CurrentUserVo user = (CurrentUserVo) event.getValue();
            if (map.get(user.getUserName()) != null) {
                HttpSession session = map.get(user.getUserName());
                session.removeAttribute(user.getUserName());
                session.invalidate();
            }
            map.put(user.getUserName(), event.getSession());
        }

    }
    /**
     * 当向session中移除数据触发
     */
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();

        if (name.equals(Constant.CURRENT_LOGIN_USER_NAME)) {
            CurrentUserVo user = (CurrentUserVo) event.getValue();
            map.remove(user.getUserName());

        }
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {

    }

    public Map<String, HttpSession> getMap() {
        return map;
    }

    public void setMap(Map<String, HttpSession> map) {
        this.map = map;
    }
}
